package vn.edu.thptduongbachmai.handlers;

import hapax.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import vn.edu.thptduongbachmai.common.Auth;
import vn.edu.thptduongbachmai.common.Configuration;

/**
 *
 * @author quytp
 */
public abstract class BaseHandler extends HttpServlet {

	private static Logger _logger = Logger.getLogger(BaseHandler.class);

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		/*
		 * forward resquest
		 */
            
            //check login
            
		if ("GET".equals(req.getMethod())) {
			this.doGet(req, resp);
		} else if ("POST".equals(req.getMethod())) {
			this.doPost(req, resp);
		}
	}

	protected String getClientIP(HttpServletRequest request) {
		return request.getRemoteAddr();
	}

	protected TemplateDataDictionary getDictionary() {
		TemplateDataDictionary dic = TemplateDictionary.create();
		return dic;
	}

	protected String applyTemplate(TemplateDataDictionary dic, String tplName, HttpServletRequest req) throws TemplateException {
		TemplateLoader templateLoader = TemplateResourceLoader.create("com/vng/zing/jsharefileadmin/view/");
		Template template = templateLoader.getTemplate(tplName);
		if (template != null) {
			dic.setVariable("static_domain", Configuration.APP_STATIC_DOMAIN);
			return template.renderToString(dic);
		}
		return "";
	}

	protected String applyTemplate(TemplateDataDictionary dic, HttpServletRequest req) throws TemplateException {
		TemplateLoader templateLoader = TemplateResourceLoader.create("com/vng/zing/jsharefileadmin/view/");
		Template template;
		template = templateLoader.getTemplate("layout");

		if (template != null) {
			Auth auth = (Auth) req.getAttribute(Auth.AUTH_KEY);
			if (auth.isLogged() && !auth.getUserName().isEmpty()) {
				TemplateDataDictionary authSession = dic.addSection("LOGIN_APP");
				authSession.setVariable("username", auth.getUserName());
			}
			dic.setVariable("static_domain", Configuration.APP_STATIC_DOMAIN);
			return template.renderToString(dic);
		}
		return "";
	}
}